import React, { createContext, useContext, useReducer, useEffect, useState } from 'react';

// 创建 Context
const TodoContext = createContext();

// 初始待办事项
const defaultTodos = [
  { id: 1, text: '完成项目提案', completed: true, category: 'work', createdAt: '2023-06-01T10:00:00Z' },
  { id: 2, text: '购买牛奶和鸡蛋', completed: false, category: 'shopping', createdAt: '2023-06-02T14:30:00Z' },
  { id: 3, text: '阅读新书', completed: false, category: 'personal', createdAt: '2023-06-03T18:15:00Z' },
  { id: 4, text: '准备会议演示文稿', completed: false, category: 'work', createdAt: '2023-06-04T09:45:00Z' },
  { id: 5, text: '购买新衣服', completed: true, category: 'shopping', createdAt: '2023-06-05T16:20:00Z' },
];

// 安全地从 localStorage 获取数据
function getSavedTodos() {
  try {
    const savedTodos = localStorage.getItem('demo3-todos');
    return savedTodos ? JSON.parse(savedTodos) : defaultTodos;
  } catch (error) {
    console.error('Failed to load todos from localStorage:', error);
    return defaultTodos;
  }
}

// Reducer 函数
function todoReducer(state, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        todos: [...state.todos, {
          id: state.nextId,
          text: action.payload.text,
          completed: false,
          category: action.payload.category,
          createdAt: new Date().toISOString()
        }],
        nextId: state.nextId + 1
      };
    
    case 'TOGGLE_TODO':
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.payload
            ? { ...todo, completed: !todo.completed }
            : todo
        )
      };
    
    case 'DELETE_TODO':
      return {
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.payload)
      };
    
    case 'INIT_TODOS':
      return {
        ...state,
        todos: action.payload,
        nextId: action.payload.length > 0 
          ? Math.max(...action.payload.map(todo => todo.id)) + 1 
          : 1
      };
    
    default:
      return state;
  }
}

// Provider 组件
export function TodoProvider({ children }) {
  // 初始状态不从 localStorage 读取
  const initialState = {
    todos: [],
    nextId: 1
  };
  
  const [state, dispatch] = useReducer(todoReducer, initialState);
  const [isInitialized, setIsInitialized] = useState(false);
  
  // 组件挂载后从 localStorage 加载数据
  useEffect(() => {
    if (!isInitialized) {
      const savedTodos = getSavedTodos();
      dispatch({ type: 'INIT_TODOS', payload: savedTodos });
      setIsInitialized(true);
    }
  }, [isInitialized]);
  
  // 将 todos 保存到 localStorage
  useEffect(() => {
    if (isInitialized) {
      try {
        localStorage.setItem('demo3-todos', JSON.stringify(state.todos));
      } catch (error) {
        console.error('Failed to save todos to localStorage:', error);
      }
    }
  }, [state.todos, isInitialized]);
  
  // 添加新的 Todo
  const addTodo = (text, category) => {
    if (text.trim() !== '') {
      dispatch({
        type: 'ADD_TODO',
        payload: { text, category }
      });
    }
  };
  
  // 切换 Todo 的完成状态
  const toggleTodo = (id) => {
    dispatch({
      type: 'TOGGLE_TODO',
      payload: id
    });
  };
  
  // 删除 Todo
  const deleteTodo = (id) => {
    dispatch({
      type: 'DELETE_TODO',
      payload: id
    });
  };
  
  // 获取特定分类的 Todo
  const getTodosByCategory = (category) => {
    return state.todos.filter(todo => todo.category === category);
  };
  
  // 获取特定 ID 的 Todo
  const getTodoById = (id) => {
    return state.todos.find(todo => todo.id === Number(id));
  };
  
  // 计算统计信息
  const getStats = () => {
    const totalTodos = state.todos.length;
    const completedTodos = state.todos.filter(todo => todo.completed).length;
    const activeTodos = totalTodos - completedTodos;
    
    const workTodos = state.todos.filter(todo => todo.category === 'work').length;
    const personalTodos = state.todos.filter(todo => todo.category === 'personal').length;
    const shoppingTodos = state.todos.filter(todo => todo.category === 'shopping').length;
    
    return {
      totalTodos,
      completedTodos,
      activeTodos,
      workTodos,
      personalTodos,
      shoppingTodos,
      completionRate: totalTodos ? Math.round((completedTodos / totalTodos) * 100) : 0
    };
  };
  
  return (
    <TodoContext.Provider value={{
      todos: state.todos,
      addTodo,
      toggleTodo,
      deleteTodo,
      getTodosByCategory,
      getTodoById,
      getStats,
      isInitialized
    }}>
      {children}
    </TodoContext.Provider>
  );
}

// 自定义 Hook 用于访问 Context
export function useTodo() {
  const context = useContext(TodoContext);
  if (!context) {
    throw new Error('useTodo must be used within a TodoProvider');
  }
  return context;
} 